package com.xx.springBootUtil.zzcache;

import com.xx.springBootUtil.util.ObjectHelper;
import com.xx.util.util.JsonUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 自定义缓存
 * @program: xunyou-parent
 * @author: zhl
 * @create: 2019-05-12
 **/
public class ZZCacheUtils {

    /**
     * 缓存
     */
    public static Map<String,ZZCache> ZZCacheMap = new HashMap<>();

    /**
     * 添加缓存
     * @param key
     * @param value
     */
    public static void set(String key,String value){
        ZZCache zzCache = new ZZCache(value,System.currentTimeMillis());
        ZZCacheMap.put(key,zzCache);
    }

    /**
     * 添加缓存  有过期时间
     * @param key
     * @param value
     * @param time 存多久 毫秒值
     */
    public static void set(String key,String value,long time){
        ZZCache zzCache = new ZZCache(value,System.currentTimeMillis(),time);
        ZZCacheMap.put(key,zzCache);
    }

    /**
     * 删除值
     */
    public static void delete(String key){
       ZZCacheMap.remove(key);
    }

    /**
     * 包含删除
     */
    public static void containDelete(String key){
        Set<String> keys = ZZCacheMap.keySet();
        if (ObjectHelper.isNotEmpty(keys)){
            for (String str : keys) {
                if (str.contains(key)){
                    ZZCacheUtils.delete(str);
                }
            }
        }
    }

    /**
     * 获取值
     */
    public static String get(String key){
        ZZCache zzCache = ZZCacheMap.get(key);
        if (zzCache==null){
            return null;
        } else {
            long createTime = zzCache.getCreateTime();
            Long time = zzCache.getTime();
            String data = zzCache.getData();
            if(time==null){
                //说明是永久保存
                return data;
            }
            if ((createTime+time)<System.currentTimeMillis()){
                //说明超时，移除
                ZZCacheMap.remove(key);
                return null;
            } else {
                return data;
            }
        }
    }
}
